<template>
  <el-form
    ref="ruleFormRef"
    style="max-width: 600px"
    :model="ruleForm"
    :rules="rules"
    label-width="auto"
    class="demo-ruleForm"
    :size="formSize"
    status-icon
  >
    <el-form-item label="Activity name" prop="username">
      <el-input v-model="ruleForm.username" />
    </el-form-item>
    <el-form-item label="Activity Password" prop="password">
      <el-input type="password" v-model="ruleForm.password" />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="submitForm(ruleFormRef)"> Create </el-button>
      <el-button @click="resetForm(ruleFormRef)">Reset</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { loginAPI } from '@/api'
import { useRouter } from 'vue-router'

interface RuleForm {
  username: string
  password: string
}

const router = useRouter()
const formSize = ref<ComponentSize>('default')
const ruleFormRef = ref<FormInstance>()
const ruleForm = reactive<RuleForm>({
  username: 'legelcoo',
  password: '@Admin123'
})

const locationOptions = ['Home', 'Company', 'School']

const rules = reactive<FormRules<RuleForm>>({
  username: [{ required: true, message: 'Please input Name', trigger: 'blur' }],
  password: [{ required: true, message: 'Please input Password', trigger: 'blur' }]
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    console.log('valid', valid, fields)
    if (valid) {
      loginFunc()
    } else {
      console.log('error submit!', fields)
    }
  })
}
const loginFunc = async () => {
  const res = await loginAPI(ruleForm)
  if (res.code === 1) {
    router.push('/')
  }
  console.log('res', res)
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
</script>
